package pomodorotasks

import java.awt.Desktop
import com.google.api.services.tasks.model.TaskLists

class PomodoroTasksController {
    // these will be injected by Griffon
    def model
    def view
    
    def currentListController
    GoogleTasksService googleTasksService

    void mvcGroupInit(Map args) {
        // this method is called after model and view are injected
        googleTasksService.initConnection(this)
    }
    
    def getAuthorizationCode(authorizeUrl, makeConnection) {
        Desktop desktop = null;
        // Before more Desktop API is used, first check 
        // whether the API is supported by this particular 
        // virtual machine (VM) on this particular host.
        if (Desktop.isDesktopSupported()) {
            desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                def uri = new URI(authorizeUrl);
                desktop.browse(uri);
            }
        } else {
            // TODO implement if there is no desktop (pre Java 6 etc)
        }


        execSync {
            String code = javax.swing.JOptionPane.showInputDialog(view.app, 
                "Please enter code shown webpage", 
                'Authorization', 
                javax.swing.JOptionPane.QUESTION_MESSAGE)
            if (code != null) {
                execOutside {
                    makeConnection(code)
                }
            }
        }
    }
    
    def updateTaskList(TaskLists taskLists) {
        model.lists.clear()
        model.lists.addAll(taskLists.items)
    }

    // void mvcGroupDestroy() {
    //    // this method is called when the group is destroyed
    // }

    
    def addAction = {
        log.debug('Adding task')
        if (currentListController != null) {
            currentListController.addAction()
        }
    }
    
    def changeListAction = { evt ->
        int selectedIndex = evt.source.selectedIndex
        if (selectedIndex >= 0) {
            def selectedList = model.lists.get(selectedIndex)
            log.debug("Changing list to $selectedList.title")
            Map members = buildMVCGroup('PomodoroTasksList', selectedList.title, rootPane: view.listsPane, 
                list: selectedList, googleTasksService: googleTasksService)
            currentListController = members['controller']
        }
    }
    
}
